import requestInterceptor from '../utils/requestInterceptor'; // 导入请求拦截器实例
import { toast } from '../utils/extendApi';
// 导入本地存储 api
import { setStorage, clearStorage } from '../utils/storage'

export const getClassList = (callback) => {
    requestInterceptor({
        url: '/classes/api/list',
        method: 'GET',
        data: {}
    }).then((res) => {
        console.log('获取班级列表成功，返回数据:', res.data);
        callback(res.data);
    }).catch((err) => {
        toast({
            title: "获取班级列表失败: " + err.message,
            icon: 'none',
            duration: 3000
        });
        callback(null);
    });
};

export const register = (userName, password, nickName, classesId, sex, status) => {
    requestInterceptor({
        url: '/app/user/api/register',
        method: 'POST',
        data: { userName, password, nickName, classesId, sex, status }
    }).then((res) => {
        console.log('注册成功，返回数据:', res.data);
        // 将用户名存储到本地变量，在登录页面进行展示
        setStorage('userName', userName)
        // 跳转回登录页面
        wx.navigateBack();
        toast({
            title: '注册成功，请登录',
            icon: 'none'
        });
    }).catch((err) => {
        toast({
            title: "注册失败: " + err.message,
            icon: 'none',
        });
    });
};

export const getClassName = (classesId, callback) => {
    requestInterceptor({
        url: '/classes/api/list',
        method: 'GET',
        data: {}
    }).then((res) => {
        let data = {
            className : '暂无班级信息',
            classesIndex : ''
        }
        for (let i = 0; i < res.data.data.length; i++) { 
            if (res.data.data[i].classesId === classesId) {
                data.className = res.data.data[i].classesName;
                data.classesIndex = i - 2; // 前2个是内蒙古大学、计算机学院
                break;
            }
        }
        callback(data);
    }).catch((err) => {
        toast({
            title: "获取班级列表失败: " + err.message,
            icon: 'none',
            duration: 3000
        });
        callback(null);
    });
};